package com.ruoyi.feike.controller;

import java.io.FileInputStream;
import java.io.InputStream;
import java.util.List;

import com.ruoyi.common.core.domain.model.LoginUser;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.feike.domain.DealercodeContract;
import com.ruoyi.feike.domain.DealercodeContractFiling;
import com.ruoyi.feike.domain.Plm;
import com.ruoyi.feike.domain.vo.ContractRecord;
import com.ruoyi.feike.domain.vo.ContractRecordThree;
import com.ruoyi.feike.mapper.ContractRecordMapper;
import com.ruoyi.feike.service.IAnnualReviewyService;
import com.ruoyi.feike.service.IContractRecordSerivce;
import com.ruoyi.feike.service.IDealercodeContractService;
import com.ruoyi.framework.web.service.TokenService;
import com.ruoyi.system.service.ISysPostService;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 【请填写功能名称】Controller
 *
 * @author ruoyi
 * @date 2022-10-27
 */
@RestController
@RequestMapping("/contract/record")
public class ContractRecordController extends BaseController
{
    @Autowired
    private IContractRecordSerivce contractRecordSerivce;

    @Autowired
    private IDealercodeContractService dealercodeContractService;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private ContractRecordMapper contractRecordMapper;

    @Autowired
    private IAnnualReviewyService annualReviewyService;

    @Autowired
    private ISysPostService postService;

    /**
     * 查询【请填写功能名称】列表
     */
    //@PreAuthorize("@ss.hasPermi('system:record:list')")
    @GetMapping("/list")
    public TableDataInfo list(ContractRecord contractRecord)
    {

        LoginUser loginUser = SecurityUtils.getLoginUser();
        boolean flag = false;
        List<String> strings = postService.selectPostListByUserId1(loginUser.getUser().getUserId());
        for (String post : strings) {
            if(post.contains("op")){
                flag = true;
                break;
            }
        }
        if(contractRecord.getDealername() !=null && ! contractRecord.getDealername().equals("")){
            String[] split = contractRecord.getDealername().split("-");
            contractRecord.setDealername(split[1]);
            contractRecord.setDealercode(split[0]);
        }
        startPage();
        List<ContractRecord> list = contractRecordSerivce.selectContractRecordList2(contractRecord);
        for (ContractRecord record : list) {
            record.setOpFlag("2");
            if(flag){
                record.setOpFlag("1");
            }
            if(contractRecord.getLimitType()!=null && contractRecord.getLimitType().equals("PART")){
                record.setLimitType("Part");
            }
        }
        return getDataTable(list);
    }

    @GetMapping("/listThree")
    public TableDataInfo listThree(ContractRecordThree contractRecordThree)
    {
        startPage();
        List<ContractRecordThree> list = contractRecordMapper.selectContractRecordThreeListEffDateisNotNull2(contractRecordThree);
        return getDataTable(list);
    }

    @Log(title = "【导出报表】", businessType = BusinessType.EXPORT)
    @GetMapping("/exportThree")
    public AjaxResult exportThree(ContractRecordThree contractRecordThree)
    {
        List<ContractRecordThree> list = contractRecordMapper.selectContractRecordThreeListEffDateisNotNull2(contractRecordThree);
        ExcelUtil<ContractRecordThree> util = new ExcelUtil<ContractRecordThree>(ContractRecordThree.class);
        return util.exportExcel(list, "record");
    }

    /**
     * 导出【请填写功能名称】列表
     */
    //@PreAuthorize("@ss.hasPermi('system:record:export')")
    @Log(title = "【导出报表】", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(ContractRecord contractRecord)
    {
        if(contractRecord.getDealername() !=null && ! contractRecord.getDealername().equals("")){
            String[] split = contractRecord.getDealername().split("-");
            contractRecord.setDealername(split[1]);
            contractRecord.setDealercode(split[0]);
        }
        List<ContractRecord> list = contractRecordSerivce.selectContractRecordList2(contractRecord);
        for (ContractRecord record : list) {
            if(contractRecord.getLimitType()!=null && contractRecord.getLimitType().equals("PART")){
                record.setLimitType("Part");
            }
        }
        ExcelUtil<ContractRecord> util = new ExcelUtil<ContractRecord>(ContractRecord.class);
        return util.exportExcel(list, "record");
    }

    /**
     * 获取【请填写功能名称】详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:record:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(contractRecordSerivce.selectContractRecordById(id));
    }

    /**
     * 新增【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:record:add')")
    @Log(title = "【新增报表】", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody ContractRecord contractRecord)
    {
        return toAjax(contractRecordSerivce.insertContractRecord(contractRecord));
    }

    /**
     * 修改【请填写功能名称】
     */
    //@PreAuthorize("@ss.hasPermi('system:record:edit')")
    @Log(title = "【修改报表】", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody ContractRecord contractRecord)
    {
        if(contractRecord.getId()!=null && contractRecord.getEffectivedate()!=null){
            ContractRecord contractRecord1 = contractRecordSerivce.selectContractRecordById(contractRecord.getId());
            int i = contractRecordSerivce.updateContractRecord(contractRecord);
            if(contractRecord1!=null && contractRecord1.getInstanceid() !=null){
                List<ContractRecord> contractRecords = contractRecordSerivce.selectContractRecordThreeList(contractRecord1);
                for (ContractRecord record : contractRecords) {
                    record.setEffectivedate(contractRecord.getEffectivedate());
                    contractRecordSerivce.updateContractRecordThree(record);
                }
            }else{
                //如果是以前的,那么都应该相同
                System.out.println("没有流程ID，查询历史");
                ContractRecord contractRecord2 = contractRecordSerivce.selectContractRecordThreeListById(contractRecord.getId());
                if(contractRecord2!=null) {
                    if (contractRecord2.getDealername().equals(contractRecord1.getDealername()) && contractRecord2.getSector().equals(contractRecord1.getSector())
                            && contractRecord2.getContracttype().equals(contractRecord1.getContracttype())) {
                        contractRecord2.setEffectivedate(contractRecord.getEffectivedate());
                        contractRecordSerivce.updateContractRecordThree(contractRecord2);
                    }
                }
            }
            ContractRecord contractRecord2 = contractRecordSerivce.selectContractRecordById(contractRecord.getId());

            annualReviewyService.saveDbLog("3","修改历史合同信息",null,null,contractRecord1,contractRecord2,"CONTRACT/Contract Record");
        }
        if(contractRecord.getId()!=null && contractRecord.getEffectivedate() ==null){
            ContractRecord contractRecord1 = contractRecordSerivce.selectContractRecordById(contractRecord.getId());
            int i = contractRecordSerivce.updateContractRecord2(contractRecord);
            if(contractRecord1!=null && contractRecord1.getInstanceid() !=null) {
                List<ContractRecord> contractRecords = contractRecordSerivce.selectContractRecordThreeList(contractRecord1);
                for (ContractRecord record : contractRecords) {
                    record.setEffectivedate(null);
                    record.setStatus(contractRecord.getStatus());
                    contractRecordSerivce.updateContractRecordThree2(record);
                }
            }else{
                //如果是以前的,那么都应该相同
                System.out.println("2没有流程ID，查询历史");
                ContractRecord contractRecord2 = contractRecordSerivce.selectContractRecordThreeListById(contractRecord.getId());
                if(contractRecord2!=null) {
                    if(contractRecord2.getDealername().equals(contractRecord1.getDealername()) && contractRecord2.getSector().equals(contractRecord1.getSector())
                            && contractRecord2.getContracttype().equals(contractRecord1.getContracttype())){
                        contractRecord2.setEffectivedate(null);
                        contractRecordSerivce.updateContractRecordThree(contractRecord2);
                    }
                }

            }
        }
        return toAjax(1);
    }

    /**
     * 删除【请填写功能名称】
     */
    @PreAuthorize("@ss.hasPermi('system:record:remove')")
    @Log(title = "【删除报表】", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(contractRecordSerivce.deleteContractRecordByIds(ids));
    }


    @PostMapping("/updateContractRecord")
    public AjaxResult updateContractRecord(@RequestBody String[] InstanceIdS)
    {
        for (String instanceId : InstanceIdS) {
            DealercodeContract  dealercodeContract =new DealercodeContract();
            dealercodeContract.setInstanceId(instanceId);
            List<DealercodeContract> dealercodeContracts = dealercodeContractService.selectDealercodeContractList(dealercodeContract);
            if(dealercodeContracts!=null && dealercodeContracts.size()>0){
                for (DealercodeContract contract : dealercodeContracts) {
                    contractRecordSerivce.update(contract);
                }
            }
        }
        return AjaxResult.success();
    }
    @Log(title = "导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<ContractRecord> util = new ExcelUtil<ContractRecord>(ContractRecord.class);
        List<ContractRecord> userList = util.importExcel(file.getInputStream());
        LoginUser loginUser = tokenService.getLoginUser(ServletUtils.getRequest());
        String operName = loginUser.getUsername();
        String message = contractRecordSerivce.importUser(userList, updateSupport, operName);
        return AjaxResult.success(message);
    }

    @GetMapping("/importTemplate")
    public AjaxResult importTemplate()
    {
        ExcelUtil<ContractRecord> util = new ExcelUtil<ContractRecord>(ContractRecord.class);
        return util.importTemplateExcel("用户数据");
    }

}
